package com.neutech.service.impl;

import com.github.pagehelper.PageHelper;
import com.neutech.arg.ProductSelectArgs;
import com.neutech.enumeration.ResultExceptionEnum;
import com.neutech.mapper.ProductMapper;
import com.neutech.service.CategoryService;
import com.neutech.service.ProductService;
import com.neutech.vo.ProductInfoVO;
import com.neutech.vo.ProductVO;
import com.neutech.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = "productCache")
public class ProductServiceImpl implements ProductService {

    private final ProductMapper mapper;
    private final CategoryService categoryService;

    @Autowired
    public ProductServiceImpl(ProductMapper mapper, CategoryService categoryService) {
        this.mapper = mapper;
        this.categoryService = categoryService;
    }

    @Override
    public ResultVO<ProductVO> selectProductById(Integer productId) {
        ProductVO productVO = mapper.selectVOById(productId);
        if (productVO == null) {
            return ResultVO.error(ResultExceptionEnum.DATA_NON_EXIST);
        }
        return ResultVO.success(productVO);
    }

    @Override
    @Cacheable(key = "#productId", unless = "#result.code != 0")
    public ResultVO<ProductInfoVO> selectProductInfoById(Integer productId) {
        ProductInfoVO infoVO = mapper.selectInfoById(productId);
        if (infoVO == null) {
            return ResultVO.error(ResultExceptionEnum.DATA_NON_EXIST);
        }

        infoSetCategoryName(infoVO);

        return ResultVO.success(infoVO);
    }

    @Override
    public ResultVO<List<ProductInfoVO>> selectPagedProductByArg(Integer page, int pageSize, ProductSelectArgs args) {
        PageHelper.startPage(page, pageSize);
        List<ProductInfoVO> products = mapper.selectAllVOByArgs(args);

        if (products == null || products.isEmpty()) {
            return ResultVO.error(ResultExceptionEnum.DATA_NON_EXIST);
        }

        //设置类别名
        for (ProductInfoVO infoVO : products) {
            infoSetCategoryName(infoVO);
        }

        return ResultVO.success(products);
    }

    private void infoSetCategoryName(ProductInfoVO infoVO){
        infoVO.setCategoryName(categoryService.getCategoryName(infoVO.getCategoryId()));
    }
}
